package com.mywebsite.Service.Impl;

import com.mywebsite.Controller.Code;
import com.mywebsite.Controller.Result;
import com.mywebsite.Dao.PictureDao;
import com.mywebsite.Domain.Picture;
import com.mywebsite.Domain.User;
import com.mywebsite.Service.PictureService;
import com.mywebsite.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


@Service
public class PictureServiceImpl implements PictureService {

    @Autowired
    PictureDao pictureDao;
    @Autowired
    UserService userService;


    @Override
    public Integer uploadpic(Integer id, String picurl) {
        Integer affected = pictureDao.uploadpic(id,picurl);
        return affected;
    }

    public Picture getById(Integer id){
        Picture picture = pictureDao.selectById(id);
        return picture;
    }

    @Override
    public Integer updatepic(Integer id, String picurl) {
        Integer affected = pictureDao.updatepic(id, picurl);
        return affected;
    }

        public Result upload(String username, String filepath) {
        System.out.println(filepath);
        User user = userService.getByName(username);
        Integer id = user.getId();
        Picture picture = this.getById(id);
        if (picture == null) {
            Integer affacted = this.uploadpic(id, filepath);
            if (affacted <= 0) {
                return new Result(Code.Error, "持久化失败");
            }
            return new Result(Code.Success, "持久化成功");
        }
        Picture picture1 = this.getById(id);
        String userpics = picture1.getpicurl();
        if (!userpics.isEmpty()) {
            Integer afted = this.updatepic(id, filepath);
            if (afted <= 0) {
                return new Result(Code.Error, "持久化失败");
            }
        }
        return new Result(Code.Success, "持久化成功");
    }
}
